<script setup>
import { ref } from 'vue'
import { LoginAPI } from '@/api/LoginRedirect.js'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.js'
const userStore = useUserStore()
const router = useRouter()
const form = ref({
  username: '',
  password: ''
})

const formcs = ref(null) //表单DOM元素

const Login = async () => {
  // 注册成功之前，先进行校验，校验成功 → 请求，检验失败 → 自动提示
  await formcs.value.validate()
  const res = await LoginAPI(form.value)
  userStore.setToken(res.token) // 调用pinia的自定义方法，将token存入pinia中
  ElMessage.success('登录成功')
  router.push('/home')
  // 用延时函数解决登录后名字显示不出的bug
  setTimeout(() => {
    router.go(0)// 模拟刷新
  }, 100);
}
</script>

<template>
  <div class="parent">
    <div class="box">
      <h1>用户登录</h1>
      <el-form label-width="55px" autocomplete="off" :model="form" ref="formcs">
        <el-form-item label="用户名">
          <el-input class="username" placeholder="请输入用户名" v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input class="password" :type="password" show-password placeholder="请输入密码" v-model="form.password">
          </el-input>
        </el-form-item>
        <div class="container">
          <el-button size="large" type="success" class="button" @click="Login">登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.parent {
  width: 100%;
  height: 90vh;
  display: grid;
  grid-template-columns: repeat(11, 1fr);
  grid-template-rows: repeat(7, 1fr);
  grid-column-gap: 0px;
  grid-row-gap: 0px;
}

.box {
  grid-area: 1 / 4 / 5 / 9;
  padding: 20px;

  .username,
  .password {
    height: 40px;
    padding: 0 10px;
    // min-width: ;
  }

  h1 {
    text-align: center;
    padding: 22px 0 22px 20px;
  }

  .container {
    display: flex;
    justify-content: center;

    .button {
      width: 50%;
      background: #5bbe9e;
    }
  }
}
</style>
